<template>
  <div :style="style">
    <Toolbar
      style="border-bottom: 1px solid #ccc"
      :editor="editor"
      :defaultConfig="toolbarConfig"
      :mode="mode" />
    <Editor
      v-model="content"
      :style="editorStyle"
      :defaultConfig="editorConfig"
      :mode="mode"
      @onCreated="onCreated"
      @onChange="onChange"/>
    <span class="wordNumber ">{{ currentLength }}/{{maxLength}}</span>
  </div>
</template>
<script>
import  '@wangeditor/editor/dist/css/style.css'
import { Editor, Toolbar } from '@wangeditor/editor-for-vue'

export default {
  components: { 
    Editor, 
    Toolbar 
  },
  props: {
    id: {
      type    : String,
      default : ''
    },
    value: {
      type    : String,
      default : ''
    },
    max: {
      type    : Number,
      default : 0
    },
    validateMaxLen: {
      type    : Boolean,
      default : false
    },
    width:{
      type    : Number,
      default : 100
    },
    height:{
      type    : Number,
      default : 500
    }
  },
  data() {
    return {
      mode          : 'default', // or 'simple'
      editor        : null,
      toolbarConfig : {
        excludeKeys:["uploadVideo","fullScreen","emotion"]//"insertTable",
      },
      editorConfig  : {
        
      },
      content       : this.value,
      currentLength : 0,
      defaultMaxLen : 20,
      validateStatus: true
    }
  },
  computed: {
    maxLength() {
      let len = this.defaultMaxLen;
      if (this.max >= 1) {
        len   = this.max;
      }
      return len;
    },
    style(){
      let res    = '';
      if(!this.validateStatus){
        res      = 'border: 2px solid #F56C6C';
      }else{
        res      = 'border: 1px solid #CCC'
      }
      if(this.width<100){
        res      = res + 'width:'+this.width+'%;'
      }
      return res
    },
    editorStyle(){
      return 'overflow-y: hidden;' + 'height:'+this.height+'px;'
    }
  },
  watch: {
    value(newVal) {
      this.content = newVal;
    },
  },
  methods: {
    onCreated(editor) {
      this.editor = Object.seal(editor) // 一定要用 Object.seal() ，否则会报错
    },
    onChange(editor){
      this.currentLength = editor.getText().length;
      this.$emit('input', this.content);
      if(editor.getText().length>this.editorConfig.maxLength){
        this.validateStatus = false
      }else{
        this.validateStatus = true
      }
    }
  },
  mounted() {
    // 模拟 ajax 请求，异步渲染编辑器
    this.$nextTick(() => {
      //this.content = '<p>模拟 Ajax 异步设置内容 HTML</p>'
      this.content = '请输入内容...'
      this.editorConfig.maxLength = this.maxLength
    })
  },
  beforeDestroy() {
    const editor = this.editor
    if (editor == null) return
    editor.destroy() // 组件销毁时，及时销毁编辑器
  }
}
</script>
<style scoped>
.wordNumber {
  color: #909399;
  background: #fff;
  text-align: right;
  z-index: 100;
  right: 10px;
  bottom: 4px;
  font-size: 12px;
  position: absolute;
}
</style>